package it.koutifaris.travianmap.context;

import it.koutifaris.travianmap.communication.mapdownloader.DownloadMapAsyncService;
import it.koutifaris.travianmap.communication.mapdownloader.DownloadMapService;
import it.koutifaris.travianmap.dal.DeleteService;
import it.koutifaris.travianmap.dal.MapServiceFactory;
import it.koutifaris.travianmap.dal.TravianServerServiceFactory;
import it.koutifaris.travianmap.dal.sqlservices.SqlMapDbHelper;
import it.koutifaris.travianmap.dal.sqlservices.SqlMapServiceFactory;
import it.koutifaris.travianmap.dal.sqlservices.deleteservice.SqlDeleteService;
import it.koutifaris.travianmap.dal.sqlservices.dumpimporter.TravianSqlDumpImporter;
import it.koutifaris.travianmap.dal.sqlservices.travianserver.SqlTravianServerServiceFactory;
import it.koutifaris.travianmap.dal.sqlservices.travianserver.TravianServerDbHelper;
import it.koutifaris.travianmap.mapsqlparser.RegexMapSqlParser;
import android.app.Activity;

public class TravianMapContextImpl implements TravianMapContext {

	private final Activity activity;
	private final TravianServerDbHelper serverDbHelper;
	private final LocaleSettings localeSettings;
	private SqlMapDbHelper currentDbHelper;
	private String currentServerId;

	TravianMapContextImpl(Activity activity) {
		this.activity = activity;
		this.serverDbHelper = new TravianServerDbHelper(activity);
		this.localeSettings = new LocaleSettingsImpl(activity);
	}

	@Override
	public MapServiceFactory getMapServiceFactory(String serverId) {
		return new SqlMapServiceFactory(this, serverId);
	}

	@Override
	public TravianServerServiceFactory getServerServiceFactory() {
		return new SqlTravianServerServiceFactory(this);
	}

	@Override
	public Activity getActivity() {
		return activity;
	}

	@Override
	public SqlMapDbHelper getSqlMapDbHelper(String serverId) {
		return new SqlMapDbHelper(activity, serverId);
	}

	@Override
	public TravianServerDbHelper getTravianServerDbHelper() {
		return serverDbHelper;
	}

	@Override
	public DownloadMapAsyncService getMapDownloader(String serverId) {
		DownloadMapService downloadMapService = new DownloadMapService(
				new TravianSqlDumpImporter(getSqlMapDbHelper(serverId).getWritableDatabase()),
				new RegexMapSqlParser());

		return new DownloadMapAsyncService(downloadMapService);
	}

	@Override
	public DeleteService getDeleteService() {
		return new SqlDeleteService();
	}

	@Override
	public LocaleSettings getLocaleSettings() {
		return localeSettings;
	}

	void setCurrentServerId(String currentServerId) {
		this.currentServerId = currentServerId;
	}

	@Override
	public String getCurrentServerId() {
		return currentServerId;
	}

	@Override
	public SqlMapDbHelper getCurrentSqlMapDbHelper() {
		if (currentDbHelper == null) {
			currentDbHelper = this.getSqlMapDbHelper(currentServerId);
		}

		return currentDbHelper;
	}

}
